package com.heima.schedule.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.heima.common.constants.ScheduleConstants;
import com.heima.common.redis.CacheService;
import com.heima.model.schedule.dtos.Task;
import com.heima.model.schedule.pojos.Taskinfo;
import com.heima.model.schedule.pojos.TaskinfoLogs;
import com.heima.schedule.mapper.TaskinfoLogsMapper;
import com.heima.schedule.mapper.TaskinfoMapper;
import com.heima.schedule.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.ExecutorService;

@Slf4j
@Service
public class TaskServiceImpl implements TaskService {

    @Autowired
    TaskinfoMapper taskinfoMapper;

    @Autowired
    TaskinfoLogsMapper taskinfoLogsMapper;

    @Autowired
    CacheService cacheService;

    @Override
    public long addTask(Task task) {
        //添加数据到数据库
        boolean dbSuccess = addTaskToDb(task);
        if(dbSuccess){
            //添加数据到缓存
            addTaskToCache(task);
        }
        return task.getTaskId();
    }


    private void addTaskToCache(Task task) {
        String key =task.getTaskType()+"_"+task.getPriority();
        //未来5分钟时间
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE,5);
        if(task.getExecuteTime()<=System.currentTimeMillis()){
            cacheService.lLeftPush(ScheduleConstants.TOPIC+key,JSON.toJSONString(task));
        }else if(task.getExecuteTime()<=calendar.getTimeInMillis()){
            cacheService.zAdd(ScheduleConstants.FUTURE+key,JSON.toJSONString(task),task.getExecuteTime());
        }
    }

    private boolean addTaskToDb(Task task) {
        //插入主表
        try{
            Taskinfo taskinfo = new Taskinfo();
            BeanUtils.copyProperties(task,taskinfo);
            taskinfo.setExecuteTime(new Date(task.getExecuteTime()));
            taskinfoMapper.insert(taskinfo);
            //插入日志表
            TaskinfoLogs taskinfoLogs = new TaskinfoLogs();
            BeanUtils.copyProperties(taskinfo,taskinfoLogs);
            taskinfoLogs.setVersion(1);
            taskinfoLogs.setStatus(ScheduleConstants.EXECUTED);
            taskinfoLogsMapper.insert(taskinfoLogs);
            task.setTaskId(taskinfo.getTaskId());
            return true;
        }catch (Exception ex){
             log.error("taks保存数据库出错了",ex.getMessage());
             return false;
        }
    }

    @Autowired
    ExecutorService executorService;

    @Scheduled(cron = "0 0/1 * * * ? ") //每1分钟执行一次
    public void refresh(){
        System.out.println("当前执行时间："+new Date());
        String token = cacheService.tryLock(ScheduleConstants.FUTURE_TASK_SYNC, 1000 * 30);
        if(StringUtils.isNotBlank(token)){
            Set<String> futurekeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
            //未来队列比较多
            if(!futurekeys.isEmpty()){
                //future_101_1->topic_101_1   future_102_2->topic_102_2
                for (String futurekey : futurekeys) {
                    //future_102_2 ->split[0] = future_
                    //               split[1] = 102_2
                    //topic_102_2
                    //异步刷
                    executorService.submit(new Runnable() {
                        @Override
                        public void run() {
                            String[] split = futurekey.split(ScheduleConstants.FUTURE);
                            String topic = ScheduleConstants.TOPIC+split[1];
                            Set<String> sortList = cacheService.zRangeByScore(futurekey, 0, System.currentTimeMillis());
                            if(!sortList.isEmpty()){
                                cacheService.refreshWithPipeline(futurekey,topic,sortList);
                            }
                        }
                    });
                }
            }
        }
    }

    @Scheduled(cron = "0 0/5 * * * ? ") //每5分钟执行一次  宕机
    @PostConstruct //宕机后数据恢复
    public void reloadDataFromDb(){
        String token = cacheService.tryLock(ScheduleConstants.FUTURE_TASK_LOAD, 1000 * 30);
        if(StringUtils.isNotBlank(token)){
            System.out.println("reloadDataFromDb --------");
            //缓存数据清空下
            clearCache(); //一致性更高 高可用
            //select * from taskinfo where time< 未来5分钟
            Calendar calendar = Calendar.getInstance();
            calendar.add(Calendar.MINUTE,5);
            LambdaQueryWrapper<Taskinfo> queryWrapper = new LambdaQueryWrapper<>();
            queryWrapper.lt(Taskinfo::getExecuteTime,calendar.getTime());
            List<Taskinfo> taskinfoList = taskinfoMapper.selectList(queryWrapper);
            if(!taskinfoList.isEmpty()){
                for (Taskinfo taskinfo : taskinfoList) {
                    Task task =new Task();
                    BeanUtils.copyProperties(taskinfo,task);
                    task.setExecuteTime(taskinfo.getExecuteTime().getTime());
                    addTaskToCache(task);
                }
            }
        }
    }

    /**
     * 缓存清空
     */
    private void clearCache() {
        //未来zset数据队列
        Set<String> futurekeys = cacheService.scan(ScheduleConstants.FUTURE + "*");
        cacheService.delete(futurekeys);
        //消费队列
        Set<String> topicKeys = cacheService.scan(ScheduleConstants.TOPIC + "*");
        cacheService.delete(topicKeys);
    }


    @Override
    public Task poll(int type, int priority) {
        while (true) {
            String jsonTask= cacheService.lRightPop(ScheduleConstants.TOPIC + type + "_" + priority);
            if(StringUtils.isNotBlank(jsonTask)){
                Task task=JSON.parseObject(jsonTask,Task.class);
                taskinfoMapper.deleteById(task.getTaskId());
                TaskinfoLogs taskinfoLogs = taskinfoLogsMapper.selectById(task.getTaskId());
                taskinfoLogs.setStatus(ScheduleConstants.EXECUTED);
                taskinfoLogsMapper.updateById(taskinfoLogs);
                return task;
            }
            return null;
        }

    }
}
